package com.neusoft.taotao.util;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * @author netboy
 *
 */
public class FileuploadUtil {
	private static final String IMAGES = "uploads";
	private static final Logger logger = LoggerFactory.getLogger(FileuploadUtil.class);

	private static String getUploadPath(ServletContext context) {
		String base = context.getRealPath(".");
		if (base != null) {
			File path = new File(base, IMAGES);
			path.mkdirs();
			return path.getAbsolutePath();
		}
		return null;
	}

	/**
	 * 
	 * @param file
	 * @return 成功返回文件信息，失败返回-null
	 */
	public static final FileResult uploadFile(ServletContext context, MultipartFile file) {
		// 获取上传目录在服务器的真实路径
		String path = getUploadPath(context);
		// 默认上传失败
		FileResult result = new FileResult(false, null);
		// 判断是否有文件需要上传
		if (path != null && file != null && !file.isEmpty()) {
			// 取出上传文件的大小
			long realSize = file.getSize();
			result.setFileSize(realSize);
			// 取出上传文件的原始名称
			String fileName = file.getOriginalFilename();
			result.setFileName(fileName);
			// 取出上传文件的后缀/类型
			String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
			result.setExtName(extName);
			// 随机生成一个新的文件名
			String uuid = UUID.randomUUID().toString();
			String newFileName = uuid + "." + extName;
			result.setServerPath(IMAGES + "/" + newFileName);
			// 编制一个上传后的文件目录
			File dest = new File(path, newFileName);
			logger.info("上传路径：  " + dest.getAbsolutePath());
			try {
				// 执行文件上传
				file.transferTo(dest);
				// 修改上传结果为上传成功
				result.setSuccess(true);
			} catch (IllegalStateException | IOException e) {
				logger.error("文件上传失败!", e);
				result.setMsg("文件上传失败！" + e.getMessage());
			}
		}
		return result;
	}
}
